import {Component, OnInit} from '@angular/core';
import {BladeContainerInterface} from '../../../../shared/blade/blade-container.interface';
import {Blade} from '../../../../shared/blade/blade.model';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {SimpleChanges} from '@angular/core/core';
import {Command} from '../../../../shared/toolbar.service';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {BladeData} from '../../../../shared/blade/blade-data';
import {MyValidators} from '../../../../utils/validator/rang';
import {ColorChoicesComponent} from '../../../../shared/color-choices/color-choices.component';

import {FaultLevel} from '../../../../entity/fault-level.model';
import {FaultLevelService} from '../../../../service/fault_level.service';
import {AlarmSoundService} from '../../../../service/alarm-sound.service';
import {DeviceCategoryService} from '../../../../service/device-category.service';

import {SoundFile} from '../../../../entity/sound-file.model'
import {DeviceCategory} from '../../../../entity/device-category.model';


@Component({
  selector: 'app-fault-level-edit',
  templateUrl: './fault-level-edit.component.html',
  styleUrls: ['./fault-level-edit.component.css']
})
export class FaultLevelEditComponent extends BladeContainerBase<FaultLevel> {
  /**
   * 声音集合
   */
  public soundFileData: SoundFile[] = [];
  /**
   * 设备分类集合
   */
  public categoryFileData: DeviceCategory[] = [];

  public original: SoundFile[] = [];

  public isChecked: boolean;
  public canUpload: boolean;


  private colorOut: {};
  private file: File;

  constructor(
    private fb: FormBuilder,
    private faultLevelService: FaultLevelService,
    private alarmSoundService: AlarmSoundService,
    private deviceCategoryService: DeviceCategoryService,
  ) {
    super(fb)
  }

  ngOnInit() {
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new FaultLevel(0, '', 0, false, '', '', 0, 0);
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TurbstatusValueListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    Promise.all([
      this.alarmSoundService.getAlarmSounds(),
      this.deviceCategoryService.getDeviceCategorys()
    ])
      .then(res => {
        this.soundFileData = [...res[0]];
        this.categoryFileData = [...res[1]];
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);


    // this.alarmSoundService.getAlarmSounds()
    // 	.then(res => {
    // 		this.original = [...res];
    // 		this.soundFileData = [...this.original];
    // 	})
    // 	.catch(error => this.bladeData.error = error)
    // 	.then(res => this.bladeData.isLoading = false);

    this.formPatchValue(this.currentEntity);
    this.isChecked = this.currentEntity.unAlarm;
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
   * 创建表单
   *
   *
   * @memberof DicKeyEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      'faultLevelName': [this.currentEntity.faultLevelName, [
        Validators.required,
        Validators.pattern('^[\u4e00-\u9fa5a-zA-Z0-9]+$'),
        Validators.maxLength(50),
      ]
        //, (control: FormControl): any => this.stateNameAsnyValidator(control, "stateName", this.currentEntity.stateName)，异步验证；
      ],
      'faultLevelColor': [this.currentEntity.faultLevelColor, [
        Validators.required,
        Validators.pattern('^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$'),
        Validators.maxLength(7)
      ]
        //, (control: FormControl): any => this.stateColorAsnyValidator(control)，异步验证颜色；
      ],
      'faultLevelColor2': [this.currentEntity.faultLevelColor,
      ],
      'unAlarm': [this.currentEntity.unAlarm,
      ],
      'soundId': [this.currentEntity.soundId,
      ],
      'deviceCategoryId': [this.currentEntity.deviceCategoryId,
      ],
    });

    //插件的颜色选择
    this.formGroup.controls['faultLevelColor2'].valueChanges.subscribe(form => {
      if (this.formGroup.controls['faultLevelColor'].value != form) {
        this.formGroup.controls['faultLevelColor'].setValue(form)
      }

    })
    this.formGroup.controls['faultLevelColor'].valueChanges.subscribe(form => {
      if (this.formGroup.controls['faultLevelColor2'].value != form) {
        this.formGroup.controls['faultLevelColor2'].setValue(form)
      }
    })
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'faultLevelName': '',
      'faultLevelColor': '',
      'soundId': '',
      'deviceCategoryId': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'faultLevelName': {
        'required': '状态名称不能为空。',
        'pattern': '状态名称必须是汉字字母数字。',
        'maxlength': '状态名称不能多于50个字符长度。',
        'exist': '状态名称已存在。',
      },
      'faultLevelColor': {
        'required': '颜色值不能为空。',
        'pattern': '颜色值只能是以#开头的数字字母。',
        'maxlength': '颜色值只能是7个字符长度。',
        'exist': '颜色值已存在。',
      },
    };
  }

  /**
   * 异步校验faultLevelName是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof turbstatusEditComponent
   */
  stateNameAsnyValidator(control: FormControl, name: string, current: any): any {
    if (!control.value || control.value == current) {
      return Observable.of(null);
    }
    return this.faultLevelService.hasStateName(control.value, this.currentEntity.faultLevelId)  //原来后边还有个name
      .map(res => res ? {exist: true} : null);
  }

  /**
   * 异步校验faultLevelColor是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof turbstatusEditComponent
   */
  stateColorAsnyValidator(control: FormControl): any {
    if (control.value == this.currentEntity.faultLevelColor) {
      return Observable.of(null);
    }
    return this.faultLevelService.hasStateColor(control.value, this.currentEntity.faultLevelId)
      .map(res => res ? {exist: true} : null);
  }

  myUploader(event) {
    this.file = event.files[0];
  }

  /**
   * 创建一个报警级别
   *
   *
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.faultLevelService.create(this.currentEntity)
        .then(res => {
          if (res.faultLevelId) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  /**
   *
   *
   *
   * @memberof TurbstatusEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();
      return this.faultLevelService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value as FaultLevel;
    this.currentEntity.faultLevelName = formValue.faultLevelName;
    this.currentEntity.faultLevelColor = formValue.faultLevelColor;
    this.currentEntity.unAlarm = formValue.unAlarm;
    this.currentEntity.soundId = formValue.soundId;
    this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
  }


  recPro(event: {}) {
    this.colorOut = event;
  }

}


// WEBPACK FOOTER //
// ./src/app/module/basic/fault-level-config/fault-level-edit/fault-level-edit.component.ts
